package com.example.ktapplication.base

import android.annotation.SuppressLint
import android.app.Activity
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.activity.OnBackPressedCallback
import androidx.annotation.IntegerRes
import androidx.fragment.app.Fragment
import androidx.lifecycle.lifecycleScope
import androidx.viewbinding.ViewBinding
import com.example.ktapplication.dialog.DialogLoading
import com.example.ktapplication.utils.ToastUtil
import com.example.ktapplication.utils.event.EventBusUtil
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch

abstract class BaseFragment<T : ViewBinding> : Fragment() {

    lateinit var binding: T

    private val currentVisibleFragment: Fragment?
        get() {
            return childFragmentManager.fragments.firstOrNull { it.isVisible }
        }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        binding = getViewBind()
        if (isRegisterEvent()) {
            EventBusUtil.eventBus.register(this)
        }
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        addOnBackPressCallBack()
        onDate(savedInstanceState)
        onViewBing()
    }

    override fun onDestroy() {
        super.onDestroy()
        try {
            if (isRegisterEvent()) {
                EventBusUtil.eventBus.unregister(this)
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    /**
     * 返回界面ui
     */
    abstract fun getViewBind(): T


    /**
     * 数据获取
     */
    abstract fun onDate(savedInstanceState: Bundle?)

    /**
     * view控件绑定
     */
    abstract fun onViewBing()

    /**
     * 是否注册eventbus事件
     */
    open fun isRegisterEvent(): Boolean {
        return false
    }

    @SuppressLint("ResourceType")
    fun showFragment(fragment: Fragment, @IntegerRes id: Int) {
        if (fragment == currentVisibleFragment) return
        val beginTransaction = childFragmentManager.beginTransaction()
        if (!fragment.isAdded || fragment.isDetached) {
            beginTransaction.add(id, fragment)
        }
        currentVisibleFragment?.let {
            beginTransaction.hide(it)
        }
        beginTransaction.show(fragment)
        beginTransaction.commit()
    }


    /**
     * binding是否已经初始化
     */
    fun viewBingIsInit(): Boolean {
        return ::binding.isInitialized
    }

    /**
     * 安全地请求activity
     */
    fun safeRequireActivity(): Activity? {
        try {
            return requireActivity()
        } catch (e: Exception) {
            e.printStackTrace()
            return null
        }
    }

    private val mDialogLoading by lazy {
        DialogLoading.instance
    }

    private var showDialog: Boolean = false

    fun showDialog(context: String, tag: String) {
        showDialog = true
        lifecycleScope.launch(Dispatchers.Main) {
            mDialogLoading.setTip(context)
            mDialogLoading.show(requireActivity().supportFragmentManager, tag)
        }
    }

    fun dismissDialog() {
        if (showDialog) {
            lifecycleScope.launch(Dispatchers.Main) {
                mDialogLoading.dismiss()
            }
        }
    }

    fun showToast(msg: String) {
        ToastUtil.showToast(requireActivity(), msg)
    }

    /**
     * 监听返回键事件
     */
    private fun addOnBackPressCallBack() {
        requireActivity().onBackPressedDispatcher.addCallback(object : OnBackPressedCallback(true) {
            override fun handleOnBackPressed() {
                if (!backPressAction()) {
                    onSysBackPress()
                }
            }
        })
    }

    /**
     * 返回键事件，是否自行处理
     */
    open fun backPressAction(): Boolean {
        return false
    }

    /**
     * 返回键事件，交由系统处理
     */
    fun OnBackPressedCallback.onSysBackPress() {
        // 取消拦截，让系统默认行为生效
        isEnabled = false
        requireActivity().onBackPressed() // 交回系统处理
        isEnabled = true // 重新启用拦截
    }
}